package com.xayq.orap.mvc;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.xayq.orap.model.User;

public class BaseController {
	/**
	 * 获取当前用户信息
	 * @return
	 */
	protected User getCurrentUserDetails(){
    	Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    	User userDetails=null;
    	if (!(auth instanceof AnonymousAuthenticationToken)) {
    		userDetails= (User) auth.getPrincipal();
    	}
    	return userDetails;
	}
	
	/**
	 * 获取request参数map
	 */
	public Map<String, String> getParameterMap(HttpServletRequest request) {
		Map<String, String> newParams = new HashMap<String, String>();
		Map params = request.getParameterMap();
		for (Object key : params.keySet()) {
			String name = (String) key;
			String[] values = (String[]) params.get(name);
			String value = values.length > 0 ? values[0].trim() : "";
			String contentType = request.getContentType();
			try {
				if (!(contentType != null && contentType.toUpperCase().contains("URLENCODED") && contentType
						.toUpperCase().contains("CHARSET"))) {
					String codeType="UTF-8";
					if(!codeType.toUpperCase().equals("UTF-8")&&!codeType.toUpperCase().equals("GB2312")
							&&!codeType.toUpperCase().equals("GBK")){
						value = new String(value.getBytes("iso-8859-1"), "UTF-8");
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			//value = StringEscapeUtils.escapeJavaScript(value);
			newParams.put(name, filterHtmlStr(filterStr(value)));
		}
		return newParams;
	}
	
	/**
     * 过滤字符串
     */
     protected static String filterStr(String str){
           if(!StringUtils.isNotEmpty(str)){
                    return str;
           }
//           str = str.replaceAll("<", "&lt;");
//           str = str.replaceAll(">", "&gt;");
//           str = str.replaceAll("\"", "&uot;");
//           str = str.replaceAll("&", "&amp;");                   
           return str;
     }
	
    /**
    * 去除html标签
    */
    public static String filterHtmlStr(String str){
          if(!StringUtils.isNotEmpty(str)){
                   return str;
          }
//          str = str.replaceAll("\u0026lt;|&lt;|\u003c", "<");
//          str = str.replaceAll("\u0026gt;|&gt;|\u003e", ">");       
//          str = str.replaceAll("<[^>]+>", "");
          return str;
    }
}
